package cn.hiapi.shopkeeper.service.order;

import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.shopkeeper.entity.order.ActivityBargainOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.jpa.order.ActivityBargainOrderJpa;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author AdinZ
 * @date 2023/1/10 11:17
 */
@Service
public class ActivityBargainOrderService extends AbsBasicService<ActivityBargainOrderJpa, ActivityBargainOrder, Long> {


    private final String KEY = "CORE:ACTIVITY:BARGAIN_ORDER";


    private String getKey(long aid, long uid) {
        return new StringBuffer().append(aid).append("_").append(uid).toString();
    }


    @Override
    public ActivityBargainOrder save(ActivityBargainOrder order) {
        super.save(order);
        if (order.getStatus() == 0)
            this.redisService.set(KEY, this.getKey(order.getAid(), order.getBuyerId()), order);
        else this.redisService.delete(KEY, this.getKey(order.getAid(), order.getBuyerId()));
        return order;
    }


    public ActivityBargainOrder getRedis(long aid, long uid) {
        ActivityBargainOrder order = this.redisService.get(KEY, this.getKey(aid, uid));
        return order;
    }


    public ActivityBargainOrder get(long aid, long uid) {
        ActivityBargainOrder order = this.getRedis(aid, uid);
        if (order == null) {
            List<ActivityBargainOrder> list = findList(new QueryWrapper().eq("aid", aid).eq("buyerId", uid).eq("status", 0));
            if (list.isEmpty()) return null;
            return list.get(0);
        }
        return order;
    }


    @Transactional
    public void payCallback(ActivityOrder order) {
        ActivityBargainOrder bargainOrder = this.get(order.getFid());
        if (bargainOrder != null) {
            bargainOrder.setStatus(1);
            bargainOrder.setUpdated(System.currentTimeMillis());
            this.save(bargainOrder);
        }
    }

    public long getParticipate(long id) {
        return this.count(new QueryWrapper().eq("aid",id));
    }
}
